var SessionManager = (function (mod) {
    // 用于添加界面的模块
    function AddPanel() {
        var wrapper = document.getElementsByClassName('wrapper')[0];
        var content = document.getElementById('content');
        var panel = document.createElement('div');
        panel.id = "Panel";
        wrapper.insertBefore(panel, content);
        return panel;
    }

    // 添加按钮，并设置其dataset属性
    function AddButtonEx(parent, caption, handler, item) {
        var btn = document.createElement('button');
        btn.innerHTML = caption;
        btn.onclick = handler;
        if (item !== null) {
            btn.dataset.key = item;
        }
        parent.appendChild(btn);
    }

    // 创建显示Session的列表
    function AddList() {
        var sessionListDiv = document.createElement('div');
        sessionListDiv.id = 'Sessions';
        var sessionList = document.createElement('ul');
        // TODO 考虑将这里也jade模板化
        for (var i = 0; i < mod.record.length; i++) {
            var item = document.createElement('li');
            item.innerHTML = '<span class="SessionList">' + mod.record.list[
                i] +
                '</span>';
            AddButtonEx(item, '另存为', listSaveSession, mod.record.list[i]);
            AddButtonEx(item, '设为当前', listSetSession, mod.record.list[i]);
            AddButtonEx(item, '查看', listShowSession, mod.record.list[i]);
            AddButtonEx(item, '重命名', listRenameSession, mod.record.list[
                i]);
            AddButtonEx(item, '导出为HTML', listExportSession, mod.record.list[
                i]);
            AddButtonEx(item, '删除', listDelSession, mod.record.list[i]);
            sessionList.appendChild(item);
        }
        $('Panel').appendChild(sessionListDiv);
        sessionListDiv.appendChild(sessionList);
        // 加根分割线
        var hr = document.createElement('hr');
        $('Sessions').appendChild(hr);
    }

    // Session列表的四个按钮对应处理函数
    function listDelSession(event) {
        if (confirm('是否删除该Session？')) {
            mod.DeleteSession(event.target.dataset.key);
            mod.Save();
            gRefreshSessionList();
        }
    }

    function listSaveSession(event) {
        var s = mod.GetSession(event.target.dataset.key);
        s.SaveAsFile();
    }

    function listSetSession(event) {
        if (confirm('是否将该Session设置为当前未关闭页面？（注意：该操作会覆盖当前未关闭页面，请谨慎操作）')) {
            mod.SetLastSessionByKey(event.target.dataset.key);
            // 调用浏览器自带的方法重新加载【上次未关闭页面】
            LastSession.init();
        }
    }

    function listShowSession(event) {
        var s = mod.GetSession(event.target.dataset.key);
        $("pageList").innerHTML = templatizer.link_list(s);
    }

    function listRenameSession(event) {
        var oldKey = event.target.dataset.key;
        var newKey = prompt('重命名Session，请输入新的名字', oldKey).trim();
        if (newKey === '') {
            alert('请不要使用空白字符');
            return;
        }
        if (newKey != oldKey) {
            mod.RenameSession(oldKey, newKey);
            gRefreshSessionList();
            mod.Save();
        }
    }

    function listExportSession(event) {
        var s = mod.GetSession(event.target.dataset.key);
        var outputHTML = templatizer.output_html(s);
        var blob = new Blob([outputHTML], {
            type: "text/plain;charset=utf-8"
        });
        saveAs(blob, s.key + '.html');
    }

    function gRefreshSessionList() {
        $('Sessions').remove();
        AddList();
    }
    // 对应Button事件
    function bRefresh() {
        LastSession.init();
    }

    function bSaveSession() {
        mod.AddLastSession();
        gRefreshSessionList();
    }

    function bSaveSessionAsFile() {
        var s = mod.GetLastSession();
        s.SaveAsFile();
    }

    function bOpenClose(event) {
        var panel = $('Panel');
        if (panel.style.display === 'none') {
            panel.style.display = 'block';
            event.target.innerText = '关闭增强工具';
        } else {
            panel.style.display = 'none';
            event.target.innerText = '打开增强工具';
        }
    }

    function bLoadFromFile() {
        var f = document.getElementById("FileInput").files[0];
        if (f) {
            var r = new FileReader();
            r.onload = function (e) {
                var content = e.target.result;
                mod.LoadSession(content);
                gRefreshSessionList();
            };
            r.readAsText(f, 'utf-8');
        } else {
            alert("Failed to load file");
        }
    }

    function bClearSession() {
        if (confirm('是否清空当前【上次未关闭页面】？（注意：该操作不可恢复，建议提前保存）')) {
            mod.ClearCurrentSession();
            // 调用浏览器自带的方法重新加载【上次未关闭页面】
            LastSession.init();
        }
    }

    function BuildGUI() {
        var panel = AddPanel();
        panel.innerHTML = templatizer.panel();
        AddButtonEx($('navigator'), '关闭增强工具', bOpenClose, null);
        AddList();
    }

    mod.handler = {
        bRefresh: bRefresh,
        bSaveSession: bSaveSession,
        bSaveSessionAsFile: bSaveSessionAsFile,
        bOpenClose: bOpenClose,
        bLoadFromFile: bLoadFromFile,
        bClearSession: bClearSession
    };
    mod.BuildGUI = BuildGUI;

    return mod;
})(window.SessionManager || {});